#include <iostream>
#include <sstream>
#include <fstream>
#include <vector>
#include <map>

using namespace std;

map<int,int> item_cache;
map<int,int> user_cache;

int user_count = 0;

fstream train;
fstream validate;

void write_to_train_file(int id, int item_id, int o){
  train << id << "," << item_id << "," << o << endl;
}

void write_to_validate_file(int id, int item_id, int o){
  validate << id << "," << item_id << "," << o << endl;
}

void write_validate_data(int id, int item_id, int o, int count, int till){
  if(count < till){
    write_to_train_file(id,item_id,o);
  }else
    write_to_validate_file(id,item_id,o);
}

int to_int(const string& s){
  if(s.length() == 0)
    return 0;
  int r;
  istringstream iss(s);
  iss >> r;
  return r;
}

int main(int argc, char** argv){
  string s;
  fstream ff;
  ff.open(argv[2]);

  train.open("train.txt",fstream::out);
  validate.open("validate.txt",fstream::out);

  if(ff.is_open()){
    while(ff.good()){
      getline(ff,s);
      istringstream iss(s);
      int item_id;
      iss >> item_id;
      item_cache[item_id] = 1;
    }
  }  
  ff.close();

  fstream f;
  f.open(argv[1]);

  vector<string> l;
  int old_id = 0;
  if(f.is_open()){
    while(f.good()){
      l.clear();

      getline(f,s);
      if(s.length() == 0)
	continue;

      istringstream iss(s);
      while(getline(iss,s,',')){
	l.push_back(s);
      }

      int user_id = to_int(l[0]);
      if(old_id == 0){
	old_id = user_id;
      }else if(old_id != 0 && old_id != user_id){
	int c = 0;
	int n = user_cache.size();
	int till = (int)(.8 * n);
	for(map<int,int>::iterator i = item_cache.begin(); i != item_cache.end();i++){
	  if(user_cache.find(i->first) == user_cache.end())
	    write_to_train_file(old_id, i->first, 0);
	  else{
	    write_validate_data(old_id, i->first, user_cache[i->first], c, till);
	    c++;
	  }
	}
	old_id = user_id;
	user_cache.clear();
      }

      user_cache[to_int(l[1])] = to_int(l[2]);
    }
  }


  train.close();
  validate.close();
  f.close();
  return 0;
}
